const fs = require('fs');
const path = require('path');
var tools = require('../../../libs/tools');
var config = require(tools.rootPath + 'config');
var { connection, pool, model } = require(tools.rootPath + 'libs/model');

const Base = require(tools.controllerPath+'common/base');
const functions = require(tools.appPath + 'functions');

module.exports = class extends Base {
    constructor() {
        super();

    }
    async __before() {
        const flag = await super.__before();
        // 如果父级想阻止后续继承执行会返回 false，这里判断为 false 的话不再继续执行了。
        if (flag === false) return false;
        return await this._auth();
    }
    async _auth() {
        this.auth = null;
        this.moduleid = 0;

        let ADMIN = await this.session('ADMIN');
        if (!ADMIN) {
            this.redirect('/welcome/index');
            return false;
        }

        this.auth = ADMIN;
        this.assign('ADMIN', ADMIN);

        //menu
        let _MENU = await this.CORE_CONF.user_menu(ADMIN['groupid'], ADMIN['userid'], this.CORE_CONF.MENU);
        this.assign({
            _MENU
        });

        //check module is exist
        if (['frameset', 'upload', 'common'].includes(this.MM)) {
            return true;
        }
        if (!this.CORE_CONF.MAP.hasOwnProperty(this.MM)) {
            this.msg(0, '模块不存在');
            return false;
        }
        this.moduleid = this.CORE_CONF.MAP[this.MM];
        let moduleid = this.CORE_CONF.MAP[this.MM];
        //check rule is exist
        if (!this.CORE_CONF.rule_exists(moduleid, this.AA)) {
            this.msg(0, this.MM + ':' + this.AA + '权限规则不存在');
            return false;
        }


        if (this.auth['groupid'] == 1) {
            return true;
        }

        if (!this.CORE_CONF.MODULE[moduleid]['is_auth']) {
            return true;
        }

        if (!this.CORE_CONF.AUTH[moduleid][this.AA]['is_auth']) {
            return true;
        }

        //check if has right
        let d = await model.find("select itemid from szh_access_back where userid=? and moduleid=? and module=? and controller=? and action=?", [this.auth['userid'], moduleid, this.MM, this.CC, this.AA]);
        if (typeof (d['itemid']) == 'undefined') {
            this.msg(0, '没有权限');
            return false;
        }

        return true;
    }
}